package com.skycode.servlet;

import com.skycode.bean.NewsBean;
import com.skycode.dao.NewsDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 1.接受post网址 /newsAdd.jsp
 * 2.接受到传递过来的新闻参数 新闻标题 新闻内容
 * 3.完成新闻添加
 * 4.跳转到其他页面
 */
@WebServlet("/newsEdit.jsp")
public class NewsUpdateServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String user =(String) req.getSession().getAttribute("User");//获取会话
        if (user == null || user.equals("")){
            resp.sendRedirect("login.jsp");//没登陆 跳转登陆页面
            return;
        }
        String newsTitle = req.getParameter("upd_NewsTitle");
        String newsContent = req.getParameter("upd_NewsContent");
        int newsId =Integer.parseInt( req.getParameter("newsId"));
        NewsBean newsBean = new NewsBean();//实例化新闻对象
        newsBean.setNewsID(newsId);
        newsBean.setNewsTitle(newsTitle);//设置新闻标题
        newsBean.setNewsContent(newsContent);//设置新闻内容
        newsBean.setAdminName("user");// todo 登陆管理员的名字
        NewsDao newsDao = new NewsDao();//实例化新闻Dao
        int result = newsDao.update(newsBean);
        if (result>0){
            resp.sendRedirect("news.jsp");//参数是相对网址
        }else {
            req.setAttribute("msg","更新失败");//错误页面显示的内容
            req.setAttribute("url","new.jsp");//显示错误信息后跳转的页面
            req.getRequestDispatcher("WEB-INF/error.jsp").forward(req,resp);
        }
    }
}
